/**
 * @angular 管理员
 * @description
 * @auth yang li
 */

role = function ($scope, $ducTools, $compile, http, $dataTableSet){
    'use strict';
    var roleTable = $('#roleTable').DataTable({
        sAjaxSource: 'system/role/query',
		fnServerData:  $ducTools.retrieveData,
        fnServerParams: function (aoData) {
            aoData.push(
                { "name": "roleName", "value": $scope.roleNameS}
            )
        },
        columns: [
            {"data": "id"},
            {"data": "roleName"},
		    {"data": null},
        ],
     	columnDefs: [
            {
                targets: 2,
                render: function (c) {
					return "<button class='btn btn-success btn-xs' ng-click=update('"+c.id+"')> 修改 </button> &nbsp;" + 
							"<button class='btn btn-info btn-xs' ng-click=deleteList('"+c.id+"')> 删除 </button> &nbsp;";
                }
            }
        ],
        createdRow: function( row, data, dataIndex ) {
            $compile(row)($scope);
        }
    });

    $dataTableSet.dataTableRowShow('roleTable');

    $scope.accountRecordDraw = function() {
        roleTable.draw();
    };
	
	//删除
	$scope.deleteList = function (id){
		swal({
			title: "确定要删除吗？",
			showCancelButton: true,
			closeOnConfirm: false,
			confirmButtonText: "确定",
			confirmButtonColor: "#046dae",
			cancelButtonText: "取消",
			animation: "slide-from-top"
		},function () {
			http.post({"roleId":id}, 'system/role/delete').then(function (res){
				swal("删除成功！");
				roleTable.draw();	
			});
		});
    };
	
	//添加修改
	$scope.addUser = function (id){
		$scope.adminId = "";
		$(id).modal('show').find("form")[0].reset();
    };
	
	//权限菜单
	http.post({"pageSize":999999,"pageNo":1}, 'system/menu/query').then(function (data) {
		var $menusp = $("#menusp");
		$menusp.html("");
		for(var i = 0;i < data.length; i++) {
			var result = data[i];
			if(result.parentName == undefined ){
				$menusp.append(
					"<li name='" + result.menuName + "' class= 'authList'>" +
					"<input name='" + result.menuName + "' ng-click='cancelChildChosed($event)' class='checkboxAll' type='checkbox' value=" + result.id + " />"
					+ result.menuName +
					"</li>"
				);
			}else{
				$("li[name='" + result.parentName + "']").after(
					"<li>" +
					"<input parentName='"+result.parentName+"' ng-click='choseParent($event)' class='checkboxAll' type='checkbox' value=" + result.id+" />" +
					"" + result.menuName + " " +
					"</li>"
				);
			}
		}
		$compile($("#menusp li"))($scope);
	})
	
	$scope.actionAll = function ($event){
        var allSelect= $("#menusp").find("input[name!='all']");
        $($event.target).prop("checked")?allSelect.prop("checked", true):allSelect.prop("checked", false);
    };
    $scope.cancelChildChosed = function ($event){
        var name = $($event.target).parent().attr("name");
        $("input[parentName='"+name+"']").prop("checked", false);
    };
    $scope.choseParent = function ($event){
        if( $($event.target).prop("checked")){
            var parentName = $($event.target).attr("parentName");
            $("li[name='"+parentName+"']").find("input[type='checkbox']").prop("checked", true);
        }
    }
	
	$scope.update = function(id) {
        $("#adminListModal2").modal('show');
		$scope.adminId = id;
		var menuspIds = [];
		var parentName = [];
		$("#menusp input").prop("checked",false);
		http.post({"id":id}, 'system/role/get').then(function (res){
			$scope.roleName = res.roleName;
			if(res.menus != undefined){
					for(var i = 0; i < res.menus.length; i++){
						menuspIds.push(res.menus[i].id);
						parentName.push(res.menus[i].parentName);
					}
				//console.log(parentName);
				setTimeout(function(){
					for (var k = 0; k < menuspIds.length; k++) {
					  var id = menuspIds[k];
					  $("#menusp input[value= " + id + "]").prop("checked", true);
					}
					for (var j = 0; j < parentName.length; j++) {
					  var name = parentName[j];
					  $("#menusp input[name= " + name + "]").prop("checked", true);
					}
				},100);		
			}
			
		});
		
    }
	$("#addAdminForm2").validate({
		rules:{
            roleName: 'required',
        },
        messages:{
            roleName:{
                required:"请输入角色名！"
            }
        },
		focusInvalid: false,
        onkeyup: false,
        submitHandler: function(){
			var _url;
			var data;
			
			var checkeds = $("input.checkboxAll:checked"),
            menuIds = "";
			
			for(var i = 0; i < checkeds.length; i++){
				if(i == (checkeds.length*1-1)){
					menuIds += checkeds.eq(i).val();
				}else{
					menuIds += checkeds.eq(i).val()+",";
				}
			}
			
			console.log(menuIds);
			if($scope.adminId == ""){
				_url = 'system/role/add'
				data = {
					"roleName":$scope.roleName,
					"menuIds":menuIds,
				};
			}else{
				_url = 'system/role/mod'
				data = {
					"id":$scope.adminId,
					"roleName":$scope.roleName,
					"menuIds":menuIds,
				};	
			}	
            http.post(data, _url).then(function (result) {
                $('#adminListModal2').modal('hide');
				swal("保存成功！")
                roleTable.draw();
            })
        },
        errorPlacement: function(error, element) {
            var $addAdminFormErrorMsg = $("#addAdminFormErrorMsg");
            if(!$addAdminFormErrorMsg.find('label').is(':visible')){
                $addAdminFormErrorMsg.html(error);
            }
            return false;
        }
    });
	
};
